/*
 * TMap Designer - A Thematic Map design software
 * Copyright (C) 2006 World Health Organization
 * http://www.who.int
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package who.tmap.toolkit.shape.impl;

import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import who.tmap.common.TMapException;
import who.tmap.toolkit.shape.MapShapes;
import who.tmap.toolkit.shape.PolygonShape;

/**
 * TMap project
 * WHO 2004-2005 
 * 
 * @author stl
 */
public class PolygonShapeImplSplitHelper extends BasePolygonShapeHelper {

    private static Logger logger = Logger.getLogger(PolygonShapeImplSplitHelper.class);      
  
    private PolygonShape shape;
    private Point2D pt1;
    private Point2D pt2;
    private PolygonShape[] polygons =null; 
    
    public PolygonShapeImplSplitHelper( PolygonShape shape, Point2D pt1, Point2D pt2 ) {
        this.shape =shape;
        this.pt1 =pt1;
        this.pt2 =pt2;
    }
    
    @SuppressWarnings("unchecked")
	public PolygonShape[] split() throws TMapException {
	    polygons =new PolygonShape[2];
	    
        List<PolygonShapePoint> allPoints =generalPathToArray( shape.getGeneralPath() );
        
        PolygonShapePoint firstPsp =findPoint( allPoints, pt1 );
        PolygonShapePoint secondPsp =findPoint( allPoints, pt2 );

        logger.debug( "firstPsp=(" + firstPsp.x + ", " + firstPsp.y + ")\nsecondPsp=(" + secondPsp.x + ", " + secondPsp.y + ")" );
        
        // Make sure the two points belong to the same shape
        if ( firstPsp.polygonId != secondPsp.polygonId ) {
            throw new TMapException( "The two points do not belong to the same polygon!");
        }
        
        // to make things easier, we only keep the polygon containing the 2 points
        List<PolygonShapePoint> thePoints =extractPointsForPolygonIdOnly( firstPsp.polygonId, (List<PolygonShapePoint>)allPoints );
         
        int polygonCt =0;
        CircularListIterator cli =new CircularListIterator( (ArrayList)thePoints );
        
        cli.iterateUntil( firstPsp );
        //cli.iterate();
        
        while ( !cli.hasTraversedAllElements() ) {
            PolygonShapePoint psp =(PolygonShapePoint)cli.iterate(); 
            
            //logger.debug( "psp=(" + psp.x + ", " + psp.y + ")" );
            
            addPoint( polygonCt, psp );
            
            if ( psp.x == pt1.getX() && psp.y == pt1.getY() ) {
                addPoint( polygonCt, secondPsp );
                polygons[ polygonCt ].getGeneralPath().closePath();

                if ( shape.getName() != null ) {
                    polygons[ polygonCt ].setName( shape.getName() + ".2" );
                }
                
                addOtherPolygons( polygons[ polygonCt ], firstPsp.polygonId, allPoints );
                break;
            } else if ( psp.x == pt2.getX() && psp.y == pt2.getY() ) {
                addPoint( polygonCt, firstPsp );
                polygons[ polygonCt ].getGeneralPath().closePath();
                
                if ( shape.getName() != null ) {
                    polygons[ polygonCt ].setName( shape.getName() + ".1" );
                }
                
                polygonCt++;
            }

        } // while         
	    
	    return polygons;
    }
    
    private void addPoint( int polygonCt, PolygonShapePoint psp ) throws TMapException {
        if ( polygons[ polygonCt ] == null ) {
            polygons[ polygonCt ] =(PolygonShape)MapShapeFactory.getInstance().getGraphic( MapShapes.POLYGON );
        }
        
        GeneralPath path =polygons[ polygonCt ].getGeneralPath();
        if ( psp.originalType != PathIterator.SEG_CLOSE ) {
	        if ( path.getCurrentPoint() != null   ) {
	            path.lineTo( psp.x, psp.y );
	        } else {
	            path.moveTo( psp.x, psp.y );
	        }        
        } 
        
    }
    
}
